﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;

namespace Planer.Model
{
    public class PeriodModel
    {
        static PeriodModel model = null;

        protected PeriodModel()
        {            
        }

        public static PeriodModel GetInstance()
        {
            if (model == null)
            {
                model = new PeriodModel();
            }

            return model;
        }

        public period GetCurrentPeriod()
        {
            var query = from per in Program.Db.periods
                        orderby per.start_date
                        where per.is_opened == "y"
                        select per;
            if (query.Count() == 0)
            {
                DateTime st = DateTime.Now;
                period p = new period()
                {
                    start_date = st,
                    finish_date = st.AddMonths(1),
                    is_opened = "y"
                };
                Program.Db.AddToperiods(p);
                Program.Db.SaveChanges();
                return p;
            }
            return query.First<period>();
        }

        public static DateTime CreateDateFromDateAndPeriod(DateTime date, periodical_action periodicalAction)
        {
            DateTime result = date.AddYears((int)periodicalAction.years)
                            .AddMonths((int)periodicalAction.months)
                            .AddDays((int)periodicalAction.days);
            return result;
        }

        public static DateTime CreateDateFromDateAndPeriod(DateTime date, allocation allocation)
        {
            DateTime result = date.AddYears((int)allocation.years)
                            .AddMonths((int)allocation.months)
                            .AddDays((int)allocation.days);
            return result;
        }

        public static string PrettyDate(DateTime Date)
        {
            return Date.ToString("d");
        }

        public static int CompareShortDates(DateTime first, DateTime second)
        {
            if (first.Year > second.Year) return 1;
            if (first.Year < second.Year) return -1;
            if (first.Month > second.Month) return 1;
            if (first.Month < second.Month) return -1;
            if (first.Day > second.Day) return 1;
            if (first.Day < second.Day) return -1;
            return 0;
        }
    }
}
